package me.leon.lib

import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.nio.charset.Charset
import java.util.*
import kotlin.collections.HashMap
import me.leon.ext.android.DeviceUtils
import me.leon.ext.java.Base64Utils
import me.leon.ext.java.toFile
import org.junit.Assert.assertEquals
import org.junit.Test

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)

        val maps = HashMap<String, MutableList<Pair<String, String>>>()
        val lists: MutableList<Pair<String, String>> = mutableListOf()
        var currentKey = ""

        "D:\\github\\Ade\\cmp_lib\\src\\test\\java\\me\\leon\\lib\\hosts".toFile().forEachLine {
            if (it.isNotEmpty()) {
                if (!it.contains("#")) parse(it)?.let { lists.add(it[1] to it[2]) }
                Regex("#(.*) Start").find(it)?.groupValues?.get(1)?.let {
                    if (it.contains(" Modified Hosts")) return@forEachLine
                    currentKey = it
                    maps.put(it, mutableListOf())
                    //                    println(it)
                }
                    ?: kotlin.run {
                        Regex("#(.*)End").find(it)?.groupValues?.get(1)?.let {
                            //                        parse(it)?.let {
                            //                            maps[currentKey]?.add(it[1] to it[2])
                            //                        }
                            //                        println("$currentKey end")
                        }
                            ?: kotlin.run {
                                if (!it.contains("#"))
                                    parse(it)?.let { maps[currentKey]?.add(it[1] to it[2]) }
                            }
                    }
            }
        }

        println(maps.size)
        println(lists)
    }

    @Test
    fun parse() {
        println(parse("54.239.96.187\taftlite-portal-nrt.amazon.co.jp")!![2])
    }

    fun parse(s: String) = Regex("(.*)\\s+(.*)").find(s)?.groupValues

    @Test
    fun device() {
        println(DeviceUtils.isDeviceRooted())
    }

    @Test
    fun hasSpace() {
        val name = "D:\\prj\\Ade\\cmp_lib\\src\\test\\java\\me\\leon\\lib\\BaseTest.java"
        //        println(is2List(FileInputStream(name), null))
        //        println(File(name).bufferedReader().readText())

        //        name.byteInputStream().buffered(8192)
        //        println(FileUtils.byte2FitMemorySize(666.toLong()))

        //        println(FileUtils.getFileLines(name))

        //        writeFileFromIS(
        //           File(File(name).parent, "copy.txt"),
        //            FileInputStream(name), false
        //
        //        )

        println(Base64Utils.encode("hello你好".toByteArray()))
        println(
            Base64.getEncoder().encode("hello你好".toByteArray()).toString(Charset.defaultCharset())
        )
        println(
            Base64Utils.decode("aGVsbG/kvaDlpb0=".toByteArray()).toString(Charset.defaultCharset())
        )
        println(
            Base64.getDecoder()
                .decode("aGVsbG/kvaDlpb0=".toByteArray())
                .toString(Charset.defaultCharset())
        )
    }

    private fun writeFileFromIS(file: File?, inputStream: InputStream?, append: Boolean): Boolean {

        if (!createOrExistsFile(file) || inputStream == null) return false

        return try {
            FileOutputStream(file, append).buffered().use {
                inputStream.buffered().use { input ->
                    while (input.read() != -1) {
                        it.write(input.readBytes())
                    }
                }
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    private fun createOrExistsFile(file: File?): Boolean {
        if (file == null) return false
        if (file.exists()) return file.isFile
        return if (!createOrExistsDir(file.parentFile)) false
        else
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
                false
            }
    }

    private fun createOrExistsDir(file: File?): Boolean {
        return file != null && if (file.exists()) file.isDirectory else file.mkdirs()
    }
}
